﻿using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Universal_tool
{
	/// <summary>
	/// MainWindow.xaml 的交互逻辑
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();

			CombineFolder.Text = Properties.Settings.Default.CombineFolder;
			CombineOutput.Text = Properties.Settings.Default.CombineOutput;
		}

		private void OnCombineBrowserClick(object sender, RoutedEventArgs e)
		{
			var openFolderDialog = new FolderBrowserDialog();
			if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
			{
				CombineFolder.Text = openFolderDialog.SelectedPath;
			}
		}

		private void OnCombineFolderStart(object sender, RoutedEventArgs e)
		{
			Properties.Settings.Default.CombineFolder = CombineFolder.Text;
			Properties.Settings.Default.CombineOutput = CombineOutput.Text;
			Properties.Settings.Default.Save();

			var files = Directory.GetFiles(CombineFolder.Text, "*.json", SearchOption.AllDirectories);
			var array = new Dictionary<string, JArray>();
			using (var streamWriter = new StreamWriter(Path.Combine(CombineFolder.Text, CombineOutput.Text), false))
			{
				foreach (var file in files)
				{
					if (file.Contains(CombineOutput.Text))
						continue;

					using (var streamReader = File.OpenText(file))
					{
						using (var reader = new JsonTextReader(streamReader))
						{
							var o = JToken.ReadFrom(reader).ToString();

							var arr = (JArray)JToken.Parse(o);
							array.Add(Path.GetFileNameWithoutExtension(file), arr);
						}
					}
				}

				streamWriter.Write(JToken.FromObject(array));
			}
		}
	}
}
